require "open-uri"
def valid_leagues
  file = File.join(Rails.root,"config","leagues.yml")
  yaml = YAML.load_file file
  yaml && yaml["leagues"] || {}
end

def league_name_to_id(content,league_name)
  regexp = %r{<tr><td>(\d+)<\/td><td>(.+?)<\/td><td>\s*#{Regexp.escape(league_name)}\s*<\/td><\/tr>}i
  if content =~ regexp
    $1
  end
end

def create_country_if_possible(country_name)
  return if country_name.blank?
  country = Country.find_or_initialize_by_name(country_name)
  returning country do |country|
    puts "country #{country.name}"
    country.save!
  end
end

def country_name_from_league_name(content,league_name)
  regexp = %r{<tr><td>(\d+)<\/td><td>(.+?)<\/td><td>\s*#{Regexp.escape(league_name)}\s*<\/td><\/tr>}i
  if content =~ regexp
    $2
  end
end


desc "Initialize data"
task :initialize=>[
  "generate:base",
  #"data:create_from_translation_table",
  "fetch:all"
]

namespace :fetch do
  desc "获取所有"
  task :all=>[
    "fetch:sports",
    #"fetch:leagues",
    "data:create_from_translation_table",
    "fetch:matches"
  ]

  desc "获取体育"
  task :sports=>"clear:sports"do
    ["Basketball","Football"].each do |sport_name|
      Sport.create :name=>sport_name
    end
  end

  desc "获取比赛赛程"
  task :matches=>:environment do
    # League.all.each{|league| league.fetch_matches}
    Sport.fetch_matches
  end

  desc "获取比赛结果"
  task :results=>:environment do
    matches = Sport.fetch_results
    puts "#{matches.size} were played."
    matches.each do |match|
      puts match.info
    end
    next_match = Match.next_match
    if next_match
      puts "next : #{next_match.info}"
    else
      puts "All matches were played."
    end
  end

  desc "获取leguest"
  task :leagues=>["clear:leagues","fetch:leagues:football","fetch:leagues:basketball","fetch:leagues:verify"] 

  namespace :leagues do
    task :football=>:environment do
      url = "http://xml.sportspunter.com/xml?function=getfullcomplist"
      content = open(url) do |f|
        f.read
      end
      start_sig = "<h3>Soccer</h3>"
      end_sig = "<h3>Table Tennis</h3>"
      regexp = %r{#{Regexp.escape(start_sig)}(.+?)#{Regexp.escape(end_sig)}}im
      content =~ regexp
      content = $1
      league_names = []
      content.scan %r{<tr><td>(\d+)<\/td><td>(.+?)<\/td><td>\s*(.+?)\s*<\/td><\/tr>}i do 
        league_names << [$2,$3]
      end

      username = SETTINGS["feed"]["username"]
      password = SETTINGS["feed"]["password"]

      leagues = valid_leagues
      league_names.each do |country_and_name|
        country_name,league_name = country_and_name.first,country_and_name.last
        puts "country #{country_name},league #{league_name}"
        unless leagues[country_name] && leagues[country_name].include?(league_name)
          next
        end
        # next unless valid_leagues.include?(league_name)
        puts "league name: #{league_name}"
        league_id = league_name_to_id(content,league_name)
        country_name = country_name_from_league_name(content,league_name)
        league = League.find_or_initialize_by_cid(league_id)
        league.name = league_name
        league.country = create_country_if_possible(country_name)
        league.sport = Sport.find_by_name("Football")
        league.feed_url = "http://xml.sportspunter.com/xml?username=#{username}&password=#{password}&format=xml&cid=#{league.cid}"
        league.save!
      end

    end

    task :verify=>:environment do
      # check all valid leagues was created.
      leagues = valid_leagues
      leagues.each do |l|
        country_name = l.first
        league_names = l.last
        league_names.each do |league_name|
          unless League.find_by_name league_name
            puts "league [#{league_name}]{#{country_name}} does not exist. Please check if the name is correct?"
          end
        end
      end
    end

    task :basketball=>:environment do
      url = "http://xml.sportspunter.com/xml?function=getfullcomplist"
      content = open(url) do |f|
        f.read
      end
      league_names = %{NBA}
      league_names.each do |league_name|
        league_id = league_name_to_id(content,league_name)
        country_name = country_name_from_league_name(content,league_name)
        league = League.find_or_initialize_by_cid(league_id)
        league.name = league_name
        league.country = create_country_if_possible(country_name)
        league.sport = Sport.find_by_name("Basketball")
        league.save!
      end

    end

  end

end
